package com.itheima.health.jobs;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.QiNiuUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;


import java.util.List;

/**
 * @program: health_parent
 * @description: 定时清理七牛云多余照片
 * @author: HuChunping
 * @create: 2021-01-11 19:54
 **/
@Component
public class CleanImgJob {

    private static final Logger log = LoggerFactory.getLogger(CleanImgJob.class);

    @Reference
    private SetmealService setmealService;

    // 启动后延迟3秒启动，每半个小时执行一次
    // @Scheduled(initialDelay = 3000, fixedDelay = 1800000)
    // 凌晨4点清理
    @Scheduled(cron = "0 0 4 * * ?")
    public void cleanImg(){
        log.info("开始清理垃圾图片");
        // 获取七牛上的所有图片
        List<String> imgIn7Niu = QiNiuUtils.listFile();
        log.debug("七牛上一共有{}张图片", imgIn7Niu.size());

        // 获取数据库里的图片setmealService
        List<String> imgInDb = setmealService.findImgs();
        log.debug("数据库一共有{}张图片", imgInDb.size());

        // 七牛当中有数据库没有的就是垃圾图片
        imgIn7Niu.removeAll(imgInDb);

        if (imgIn7Niu.size() > 0) {
            log.debug("需要删除的图片一共有{}张", imgIn7Niu.size());
            // List.toArray(某类型数组) ====》返回某类型数组(下面得代码是将集合转字符串数组)
            QiNiuUtils.removeFiles(imgIn7Niu.toArray(new String[]{}));

        } else {
            log.debug("没有需要删除的图片");
        }
        log.info("清理垃圾图片完成......");
    }
}












